<template>
	<van-form @submit="onSubmit">
		<van-nav-bar title="登录" left-text="" left-arrow @click-left="onClickLeft" />
		<van-cell-group inset>
			<van-field v-model="username" name="username" label="用户名" placeholder="用户名"
				:rules="[{ required: true, message: '请填写用户名' }]" />
			<van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
				:rules="[{ required: true, message: '请填写密码' }]" />
		</van-cell-group>
		<div style="margin: 16px;">
			<van-button id="btn" round block type="primary" native-type="submit" >
				登录
			</van-button>
		</div>
		<div>
			<router-link to="/regist" id="wj">
				忘记密码
			</router-link>
		</div>
		<div>
			<router-link to="/regist" id="zc">
				立即注册
			</router-link>

		</div>
	</van-form>

</template>

<script lang="ts" setup>
	import {ref} from 'vue'
	import {loginUser} from '@/api/user'
	import {Toast} from 'vant'
	import 'vant/es/toast/style';
	import router from '@/router'
		// 使用userStore
	import {useUsersStore} from '@/store/user'
	const store = useUsersStore()

	const username = ref("")
	const password = ref("")

	const onSubmit = (data) => {
		console.log('submit', data);
		store.loginUser(data)
			.then(res => {
				console.log('submit', res)
				if (res.code != 0) {
					// ${res.message} 
					Toast({
						message: res.message,
						position: 'top',
					});
					console.log(`用户登录失败`);
					}
				else {
					Toast({
						message: "用户登录成功",
						position: 'top',
					});
					localStorage.setItem("username", res.data.username)
					router.push({
									name:"home",
									query: {date:new Date().getTime()}
									})
					console.log("登录成功")

				}
			})
			.catch(err => {
				Toast({
					message: "服务端错误！",
					position: 'top',
				});
				console.log(err, `服务端错误！`)
			})
	};
</script>

<style>
	#wj {
		float: left;
		padding-left: 20px;
	}

	#zc {
		float: right;
		margin-top: 2px;
		padding-right: 20px;
	}
</style>
